load("./PredModel.RData")
library(caret)
## library(foreach)
## library(doParallel)
## cl <- makeCluster(4)
## registerDoParallel(cl)

### Start with history value
initData <- x.train[1,]
initDataXY <- cbind(initData,y.train[1])
bestData <- dat[which.max(dat[,ncol(dat)]),c(PredModel$finalModel$xNames,"Y2")]
simData <- initData
predValue <- predict(PredModel,newdata=simData)


iter <- 2000000
result <- matrix(ncol=(ncol(simData)+1),nrow=1)
## foreach( i = 1:1000000 ) %dopar%
##     noise <- rnorm(ncol(simData),0,1)
##     simData <- simData + noise
##     new <- cbind(simData,predict(PredModel,newdata=simData))
##     cat(paste(new,"\n"))
##     result[i+1,] <- new
## }    

mem <- initData[,ncol(initData)]
resultFull <- matrix(ncol=ncol(initData)+1,nrow=iter)

simData <- x.train[1,]
simData[1,] <- runif(ncol(simData),-2,2)
for(i in 1:iter)
{
    noise <- runif(ncol(simData),-2,2)
    simData[1,] <-simData[1,] +  noise 
    new <- predict(PredModel,newdata=simData)
    resultFull[i,] <- as.matrix(cbind(simData,new))
    if(new > mem)
    {
        print(paste("Y=",new,"Iter=",i))
        mem <- new
        result <- cbind(simData,new)
    }

    if (iter %% 100 == 0 )
    {
        plot(resultFull[,1],resultFull[,2],type='l')
        points(simData[1,1],simData[1,2],col='red',pch=4)
    }
}

resultFullOrder <- resultFull[order(resultFull[,ncol(resultFull)],decreasing=T),]
resultFullOrder[,10] <- round(resultFullOrder[,10],4)
resultSubsetOrder <- resultFullOrder[!duplicated(resultFullOrder[,10]),][1:300,]

head(resultSubsetOrder)

direction <- ((resultFullOrder[1,] - bestData)/bestData)[1,]
sign(direction)

library(plotly)
plot_ly(x=resultSubsetOrder[,1],y=resultSubsetOrder[,3],z=resultSubsetOrder[,10],type='contour')



png("./modelsim.png",width=1366,height=768)
par(mfrow=c(2,5))
for (i in 1:9)
{
    smoothScatter(x=resultFull[1:200,i], y=resultFull[1:200,10],main=slctVariable[i,1],xlab=slctVariable[i,1],ylab="Y")
}
dev.off()


